package main

import (
	"AutoPacConfig/src/config"
	"AutoPacConfig/src/controller"
	"AutoPacConfig/src/data/dto"
	"AutoPacConfig/src/middleware"
	"AutoPacConfig/src/tool"
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/sync/errgroup"
	"gorm.io/gorm"
)

var (
	g   errgroup.Group
	ip  string
	gdb *gorm.DB
)

func main() {
	ip = tool.GetIP()
	fmt.Println("当前的ip地址:", ip, "time:04-09 1357")
	fmt.Println("test1234")

	gdb = config.OpenDb()
	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()

	//自动迁移
	err := gdb.AutoMigrate(&dto.ProxyConfig{}, &dto.ProxyDomain{}, &dto.ProxyDomainCategory{})
	if err != nil {
		panic(err)
		return
	}

	//TODO:需要提供的接口大致如下:
	//1.获取域名列表(全部,已启用代理域名,未启用代理域名)
	//2.添加域名,删除域名,修改域名
	//3.添加,删除,修改域名类别
	//4.更新域名是否使用代理
	//5.更新代理的地址和端口

	c := controller.NewController()
	v1 := router.Group("/pac")
	{
		domains := v1.Group("/domain")
		{
			domains.GET("getDomains", c.GetProxyDomain)
		}
	}

	router.GET("/autoPacConfig", func(c *gin.Context) {
		var result []dto.ProxyDomain

		//Select id,match_tail_domain,cid from proxy_domain WHERE cid IN (SELECT id from proxy_domain_category WHERE is_enable = 1) AND deleted_at is NULL AND is_match_domain_suffix=1
		res := config.Gdb.Table("proxy_domain").
			Select("id,match_tail_domain,cid").
			Where("cid  in  (?)", gdb.
				Table("proxy_domain_category").
				Select("id").
				Where("is_enable=1")).
			Where("deleted_at is NULL AND is_match_domain_suffix=1").
			Find(&result)
		if res.Error != nil {
			middleware.Fail(c, http.StatusInternalServerError, "获取代理域名失败", "")
		}

		//测试拼接pac文件
		var builder strings.Builder
		builder.WriteString("function FindProxyForURL(url, host) {\n")
		builder.WriteString("if (isPlainHostName(host) || \n")
		builder.WriteString("        host === \"localhost\" ||\n")
		builder.WriteString("        isInNet(dnsResolve(host), \"10.0.0.0\", \"255.0.0.0\")) {\n")
		builder.WriteString("        return \"DIRECT\";\n")
		builder.WriteString("    }\n")

		builder.WriteString("    const PROXY_DOMAINS = [\n")
		//匹配要代理的域名
		for _, pd := range result {
			builder.WriteString("        \"")
			builder.WriteString(pd.MatchTailDomain)
			builder.WriteString("\"")
			builder.WriteString(",\n")
		}
		builder.WriteString("    ];\n")

		builder.WriteString("    for (let i = 0; i < PROXY_DOMAINS.length; i++) {\n")
		builder.WriteString("        if (host.endsWith(PROXY_DOMAINS[i])) {\n")
		//代理的服务器地址,端口
		builder.WriteString("            return \"PROXY 192.168.1.113:8888; \" + \n")
		builder.WriteString("                   \"DIRECT\";\n")
		builder.WriteString("        }\n")
		builder.WriteString("    }\n")

		builder.WriteString("    return \"DIRECT\";\n")
		builder.WriteString("}\n")

		c.Header("Content-Type", "application/x-ns-proxy-autoconfig")
		c.String(http.StatusOK, builder.String())
	})

	//运行多个服务
	server := &http.Server{
		Addr:         "0.0.0.0:8083", //ip+":8083"
		Handler:      router,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	g.Go(func() error {
		//FIXME:使用https
		//return server.ListenAndServeTLS("/Users/gosha/Desktop/GoWork/nginx.crt",
		//	"/Users/gosha/Desktop/GoWork/nginx.key")

		return server.ListenAndServe()
	})

	if err := g.Wait(); err != nil {
		log.Fatal(err)
	}
	return
}
